const app = getApp();
import constants from '../js/const.js';
const util = require('../utils/util.js');
/**
 * routerFillter --全局路由拦截器
 * @function
 * @param{Object} pageObj 当前页面的page对象
 * @param{Boolean} isAuth 是否开启权限判断
 */

exports.routerFilter = function (pageObj) {
    let onLoad = pageObj.onLoad;
    pageObj.onLoad = function (options) {
        onLoad.call(this,options);
    };
    //如果选择不登录，进入登录页面
    pageObj.isLogin = function (params, callback,unloginCallback) {
        util.promise("/isLogin").then(function (res) {
            if (!res.data) {
                if(unloginCallback){
                    unloginCallback();
                }else{
                    wx.showModal({
                        title: '您还未登录',
                        content: '请您先登录',
                        success(res) {
                            if (res.confirm) {
                                wx.getSetting({
                                    success: (res) => {
                                        // if (!res.authSetting['scope.userInfo']) {
                                        wx.getUserProfile({
                                            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                                            success: (res) => {
                                                let userInfo=res.userInfo;
                                                wx.login({
                                                    success(res) {
                                                        if (res.code) {
                                                            util.promise('/getOpenId', res.code
                                                            ).then(res => {
                                                                util.setStorageSync(constants.cache_key.SESSION_KEY,res.data[constants.cache_key.SESSION_KEY]);
                                                                util.setStorageSync(constants.cache_key.OPENID,res.data[constants.cache_key.OPENID]);
                                                                userInfo= util.extend(userInfo,res.data);
                                                                wx.navigateTo({
                                                                    url: '/pages/my/register',
                                                                    events: {
                                                                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                                                                        acceptDataFromOpenedPage: function (data) {
                                                                            console.log(data)
                                                                        },
                                                                        someEvent: function (data) {
                                                                            console.log(data)
                                                                        }
                                                                    },
                                                                    success: function (res) {
                                                                        // 通过eventChannel向被打开页面传送数据
                                                                        res.eventChannel.emit('acceptDataFromOpenerPage',userInfo)
                                                                    }
                                                                })

                                                            });
                                                        }
                                                    }
                                                });
                                            }
                                        })
                                    }
                                });

                            } else if (res.cancel) {

                            }
                        }
                    });
                }
            } else {
                callback();
            }
        })


    };

    pageObj.onClose = function (e) {
        let that = this;
        that.setData({showLoginDialog: false});
        wx.reLaunch({url: '/pages/product/searchProduct'});
    };
    pageObj.login = function (event) {
        let that = this;
        let thatData = that.data;
    };
    //input改变改变文本框内值
    pageObj.inputEdit = function (e) {
        let dataset = e.currentTarget.dataset;
        let value = e.detail;
        value = value && dataset.isUpper ? value.toUpperCase() : value;
        util.setItemValue(this.data, dataset.item, value);
        this.setData(this.data);
        if (dataset.callback) {
            return pageObj[dataset.callback].call(this, null, value);
        } else if (this.inputEditCallback) {
            this.inputEditCallback();
        }
    };

    pageObj.showTerms = function (event) {
        let dataset = event.currentTarget.dataset;
        let data = {[dataset.key]: true};
        this.setData(data,function (){
            if (dataset.callback) {
                pageObj[dataset.callback].call(this,event);
            }
        });

    };
    pageObj.closeTerms = function (event) {
        let dataset = event.currentTarget.dataset;
        let key = dataset.key;
        this.setData({[key]: false},function (){
            if (dataset.callback) {
                pageObj[dataset.callback].call(this);
            }
        });

    };
    pageObj.selectTerm=function (event) {
        let data= this.data;
        let dataset=event.currentTarget.dataset;
        data.showKeyboard=false;
        util.setItemValue(data,dataset.key,false);
        util.setItemValue(data,dataset.code,event.detail.code);
        util.setItemValue(data,dataset.name,event.detail.name);
        this.setData(data,function (){
            if (dataset.callback) {
                pageObj[dataset.callback].call(this);
            }
        });
    };

    pageObj.selectDate=function(event){
        let dataset = event.currentTarget.dataset;
        let data=this.data;
        util.setItemValue(data,dataset.model,util.formatDate(new Date(event.detail)));
        this.setData(data,function (){
            this.closeTerms(event);
        });

    };
    pageObj.selectChange=function(event){
        let dataset = event.currentTarget.dataset;
        let data=this.data;
        util.setItemValue(data,dataset.model,event.detail);
        this.setData(data);
    };
    pageObj.changeSearchValue = function (event) {
        this.setData({hideHistory: event.detail ? true : false});
        let callback = event.currentTarget.dataset.callback;
        if (callback) {
            pageObj[callback].call(this, event);
        }
    };
    pageObj.setBackhomeDefaultPosition = function (width, height) {
        let windowWidth = width || this.data.windowWidth;
        let windowHeight = height || this.data.windowHeight;
        this.setData({
            left: windowWidth - constants.MOVE_VIEW_RADIUS - 10, //默认显示位置 left距离
            top: windowHeight / 2  //默认显示位置 top距离
        })
    };
    pageObj.initBackhomePosition = function () {
        let that = this;
        that.setBackhomeDefaultPosition();
    };
    pageObj.backHome = function () {
        wx.reLaunch({
            url: '/pages/product/searchProduct'
        })
    };

    /**
     * 拖拽移动(补丁)
     */
    pageObj.handleMoveViewPos = function (e) {
        // 在ios下永远都不会走这个方案，以免引起无用的计算
        if (!this.data.ios) {
            const touchPosX = e.touches[0].clientX;
            const touchPosY = e.touches[0].clientY;
            const moveViewCenterPosX = this.data.left + constants.MOVE_VIEW_RADIUS;
            const moveViewCenterPosY = this.data.top + constants.MOVE_VIEW_RADIUS;
            // 确保手指在悬浮窗上才可以移动
            if (Math.abs(moveViewCenterPosX - touchPosX) < constants.MOVE_VIEW_RADIUS && Math.abs(moveViewCenterPosY - touchPosY) < constants.MOVE_VIEW_RADIUS) {
                if (touchPosX > 0 && touchPosY > 0) {
                    this.setData({
                        left: touchPosX - constants.MOVE_VIEW_RADIUS,
                        top: touchPosY - constants.MOVE_VIEW_RADIUS
                    })
                } else {
                    this.setBackhomeDefaultPosition();
                }
            }
        }
    };
    /**
     * 拖拽移动
     */
    pageObj.handleTouchMove = function (e) {
        const touchPosX = e.touches[0].clientX;
        const touchPosY = e.touches[0].clientY;
        if (touchPosX > 0 && touchPosY > 0) {
            this.setData({
                left: touchPosX - constants.MOVE_VIEW_RADIUS,
                top: touchPosY - constants.MOVE_VIEW_RADIUS
            });
        } else {
            this.setBackhomeDefaultPosition();
        }
    };
    /**
     * 用户点击右上角分享
     */
    pageObj.onShareAppMessage = function () {
        let data = this.data;
        let url = this.route;
        let options = this.options;
        let urlWithArgs = `${url}?isShare=1`;
        for (let key in options) {
            let value = options[key];
            urlWithArgs += '&' + key + '=' + value
        }
        return {
            path: `/${urlWithArgs}`,
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    };
    pageObj.navigateTo=function (url,acceptDataFromPage,acceptDataToPage){
        wx.navigateTo({
            url: url,
            events: {
                acceptDataFromPage: acceptDataFromPage
            },
            success: acceptDataToPage
        });
    }
    return Page(pageObj);
};